package leetcode.f1t100;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 给出字符串数组s, 和定长字符串数组words, 输出所有出现且仅一次出现所有单词的起始位置
 * https://leetcode.com/problems/substring-with-concatenation-of-all-words/
 *
 * @author lichx
 * @date 2021/12/16 17:01
 */
public class Q30_SubStringConcatAllWords {

    public static void main(String[] args) {
        String s = "wordgoodgoodgoodbestword";
        String[] words = new String[]{"word","good","best","good"};
        List<Integer> list = new Q30_SubStringConcatAllWords().findSubstring(s, words);
        for (Integer i : list) {
            System.out.println(i);
        }
    }

    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> ans = new ArrayList<>();
        HashMap<String, Integer> wordsCount = new HashMap<>();
        for (String word : words) {
            wordsCount.put(word, wordsCount.getOrDefault(word, 0) + 1);
        }
        int sLen = s.length();
        int num = words.length;
        int wLen = words[0].length();
        for (int i = 0; i < sLen - num * wLen + 1; i++) {
            int j = 0;
            HashMap<String, Integer> matchWords = new HashMap<>();
            while (j < num) {
                String curWord = s.substring(i + j * wLen, i + (j + 1) * wLen);
                if (wordsCount.containsKey(curWord) && matchWords.getOrDefault(curWord, 0).compareTo(wordsCount.get(curWord)) < 0) {
                    matchWords.put(curWord, matchWords.getOrDefault(curWord, 0) + 1);
                    j++;
                } else {
                    break;
                }
            }
            if (j == num) {
                ans.add(i);
            }
        }
        return ans;
    }
}
